package com.syqc.monitor.popup

import android.annotation.SuppressLint
import android.view.animation.AlphaAnimation
import androidx.activity.viewModels
import androidx.core.view.isVisible
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import autodispose2.autoDispose
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.Marker
import com.amap.api.navi.AmapNaviPage
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.google.gson.reflect.TypeToken
import com.syqc.maps.utils.MapUtil
import com.syqc.adapter.CarInfoAdapter
import com.syqc.adapter.OperInfoAdapter
import com.syqc.base.BaseMapActivity
import com.syqc.comlib.AppConfigs
import com.syqc.comlib.MenuKey
import com.syqc.comlib.UserConstant
import com.syqc.comlib.databinding.IncludeRecyclerMathBinding
import com.syqc.comlib.rx.LiveDataBus
import com.syqc.comlib.rx.filterFast
import com.syqc.comlib.utils.GsonUtil
import com.syqc.comlib.utils.ScreenUtil
import com.syqc.comlib.utils.showToast
import com.syqc.comlib.utils.startActivityTo
import com.syqc.comlib.utils.toast
import com.syqc.entity.VideoAlarm
import com.syqc.login.FunKey
import com.syqc.login.FunType
import com.syqc.login.InfoSetModel
import com.syqc.login.LocationStatusModel
import com.syqc.maps.utils.BitmapUtil
import com.syqc.maps.utils.MarkerSet
import com.syqc.maps.utils.NaviActivity
import com.syqc.maps.utils.PopupVM
import com.syqc.monitor.R
import com.syqc.monitor.databinding.IncludeCarMapInfoBinding
import com.syqc.monitor.databinding.PopupRealVideoBinding
import com.syqc.monitor.ui.carinfo.CarInfoActivity
import com.syqc.monitor.ui.set.InfoSet2Activity
import com.syqc.monitor.ui.tyre.TyreInfoActivity
import com.syqc.monitor.utils.ActivityUtil
import com.syqc.utils.ColorUtil
import com.syqc.utils.DataUtil
import com.syqc.utils.Keys
import com.syqc.utils.ToolsUtil
import com.syqc.utils.Units
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers

class PopupActivity : BaseMapActivity<PopupRealVideoBinding>(PopupRealVideoBinding::inflate) {
    private var mMarker: Marker? = null

    //是否展示彈窗
    private var isShowPopup = true

    //是否移动
    private var isMove = true

    private var mLatLng: LatLng? = null

    private lateinit var mInfoVB: IncludeCarMapInfoBinding
    private val mViewModel by viewModels<PopupVM>()
    private val mDriversPopup by lazy { DriversPopup(this) }
    override fun initMap() {
        mAMap.uiSettings.run {
            //缩放按钮
            isZoomControlsEnabled = false
            //旋转功能
            isRotateGesturesEnabled = false
            //双指倾斜手势
            isTiltGesturesEnabled = false
            //定位按钮
            isMyLocationButtonEnabled = false
            //开启比例尺
            isScaleControlsEnabled = true
        }

        mAMap.setOnMarkerClickListener {
            if (mViewModel.gpsDetail != null && num == 540) {
                MapUtil.showLatLngZoom(mAMap, mLatLng!!)
                mInfoVB.llCarInfo.isVisible = true
                initInfo()
            }
            return@setOnMarkerClickListener true
        }
    }

    private lateinit var mRecyclerVB: IncludeRecyclerMathBinding
    override fun initView() {
        BitmapUtil.initLruCache()
        mInfoVB = IncludeCarMapInfoBinding.bind(binding.root)
        mRecyclerVB = IncludeRecyclerMathBinding.bind(binding.root)
        mRecyclerVB.recyclerView.layoutManager = LinearLayoutManager(this)
        mRecyclerVB.recyclerView.adapter = mAdapter
        val carId = intent.getStringExtra(Keys.INTENT_CAR_ID)
        mViewModel.carId = carId
        initAlarms()

        infoView()
        initData()
        infoEvent()

        val anima = AlphaAnimation(0f, 1f)
        anima.duration = 2000
        binding.flBackground.startAnimation(anima)
        ToolsUtil.startAmin(binding.ivRefresh)
        val layoutParams = binding.llReal.layoutParams
        layoutParams.height = ScreenUtil.dp2px(this, 240)
        binding.llReal.layoutParams = layoutParams
        isShowPopup = false
        mInfoVB.llCarInfo.isVisible = false
    }

    override fun setListener() {

        binding.rdbMapCarInfo.setOnClickListener {
            binding.flPopLocation.isVisible = true
            mRecyclerVB.recyclerView.isVisible = false
        }
        binding.rdbMapLocation.setOnClickListener {
            binding.flPopLocation.isVisible = false
            mRecyclerVB.recyclerView.isVisible = true
        }
        binding.ivPopupClose.setOnClickListener {
            finish()
        }

        binding.ivCarCarLocation.filterFast {
            if (num == 240) return@filterFast
            MapUtil.showLatLngZoom(mAMap, mLatLng!!)
            if (mViewModel.gpsDetail != null) {
                mInfoVB.llCarInfo.isVisible = true
                initInfo()
            }
        }
        //放大
        binding.ivMapZoomIn.setOnClickListener {
            mAMap.animateCamera(CameraUpdateFactory.zoomOut(), 600, null)
        }

        //缩小
        binding.ivMapZoomOut.setOnClickListener {
            mAMap.animateCamera(CameraUpdateFactory.zoomIn(), 600, null)
        }

        binding.ivMapSet.setOnClickListener {

            showMore()

        }
    }

    private fun showMore() {
        val layoutParams = binding.llReal.layoutParams
        num = if (num == 240) {
            isShowPopup = true
            mInfoVB.llCarInfo.isVisible = true
            540
        } else {
            isShowPopup = false
            mInfoVB.llCarInfo.isVisible = false
            240
        }
        layoutParams.height = ScreenUtil.dp2px(this, num)
        binding.llReal.layoutParams = layoutParams
        if (mLatLng == null) return
        if (num == 240) {
            MapUtil.showMapLatLngZoom(mAMap, mLatLng!!)
        } else {
            initInfo()
            if (AppConfigs.isCenter) {
                MapUtil.showMapLatLng(mAMap, mLatLng!!)
            } else {
                MapUtil.showLatLngZoom(mAMap, mLatLng!!)
            }
        }
    }

    private var num = 240

    private val mInfoAdapter by lazy { CarInfoAdapter() }
    private fun infoView() {
        mInfoVB.recyclerCarInfo.layoutManager = LinearLayoutManager(this)
        mInfoVB.recyclerCarInfo.adapter = mInfoAdapter

        handleOper()

    }

    private fun initData() {

        mViewModel.toastObserver()
            .observeOn(AndroidSchedulers.mainThread()).autoDispose(scopeProvider)
            .subscribe(this::toastObserver)

        mViewModel.locationSub.hide().autoDispose(scopeProvider).subscribe {
            it.run {
                if (glat.isEmpty() || glng.isEmpty()) return@run
                mLatLng = LatLng(glat.toDouble(), glng.toDouble())
                val bitmapDes =
                    MarkerSet.getBitmapDes(
                        this@PopupActivity,
                        carId, state, drct, carName, carPlate, iconLink, mViewModel.isPlate, speed
                    )
                if (mMarker == null) {
                    mMarker = MapUtil.addAndGetMarker(mAMap, mLatLng!!, bitmapDes)
                } else {
                    mMarker?.run {
                        position = mLatLng
                        setIcon(bitmapDes)
                    }
                }
                if (isShowPopup) {
                    mInfoVB.llCarInfo.isVisible = true
                    initInfo()
                }
                if (num == 240) {
                    MapUtil.showMapLatLngZoom(mAMap, mLatLng!!)
                } else {
                    if (isMove) {
                        isMove = false
                        MapUtil.showLatLngZoom(mAMap, mLatLng!!)
                    }
                }

                if (AppConfigs.isCenter) {
                    MapUtil.showMapLatLng(mAMap, mLatLng!!)
                }
                videoAlarmTypes?.let { item ->
                    alarmsEntity[0].isNormal = item.contains("vsm")
                    alarmsEntity[1].isNormal = item.contains("vsh")
                    alarmsEntity[2].isNormal = item.contains("vsb")
                    alarmsEntity[3].isNormal = item.contains("vtb")
                    alarmsEntity[4].isNormal = item.contains("vsv")
                }

                mAdapter.setList(alarmsEntity)
            }
        }
        //时间刷新监听
        mViewModel.timeObserver().observeOn(AndroidSchedulers.mainThread())
            .autoDispose(scopeProvider).subscribe {
                if (it == 1) {
                    ToolsUtil.stopAmin(binding.ivRefresh)
                    ToolsUtil.startAmin(binding.ivRefresh)
                }
                if (it / 3600 > 0) {
                    binding.tvRefreshTime.text = "${it / 60}${getString(R.string.unit_minute_)}"
                } else if (it / 60 > 0) {
                    binding.tvRefreshTime.text = "${it / 60}${getString(R.string.unit_minute_)}"
                } else {
                    binding.tvRefreshTime.text = "${it}${getString(R.string.unit_second_)}"
                }
            }
    }

    private fun showInfoRecycler() {
        mInfoAdapter.setList(LocationStatusModel.upData(mViewModel.gpsDetail))
    }

    //是否展示列表
    private var isShowRecycler = AppConfigs.isMapInfoOpen

    /** 设置info点击事件 */
    private fun infoEvent() {
        LiveDataBus.get().with("upInfoState").observe(this) {
            if (mViewModel.carId.isNullOrEmpty()) return@observe
            mViewModel.refresh()
        }
        mInfoVB.ivUpDown.isSelected = isShowRecycler
        if (isShowRecycler) {
            showInfoRecycler()
            mInfoVB.recyclerCarInfo.isVisible = true
        } else {
            mInfoVB.recyclerCarInfo.isVisible = false
        }
        mInfoVB.ivTyre.isVisible = UserConstant.current_ip != "113.105.152.93"
        mInfoVB.ivUpDown.setOnClickListener {
            isShowRecycler = !isShowRecycler
            mInfoVB.ivUpDown.isSelected = isShowRecycler
            if (isShowRecycler) {
                showInfoRecycler()
                mInfoVB.recyclerCarInfo.isVisible = true
            } else {
                mInfoVB.recyclerCarInfo.isVisible = false
            }
        }

        mInfoVB.ivCarSet.setOnClickListener {
            if (ToolsUtil.isFastClick()) return@setOnClickListener
            startActivityTo<InfoSet2Activity>(this)
        }

        mInfoVB.ivCarClose.setOnClickListener {
            isShowPopup = false
            mInfoVB.llCarInfo.isVisible = false
        }

        mInfoVB.ivCarRefresh.setOnClickListener {
            if (ToolsUtil.isFastClick()) return@setOnClickListener
            mViewModel.refresh2()
        }


        mInfoVB.ivTyre.setOnClickListener {
            mViewModel.gpsDetail?.let {
                val list = LocationStatusModel.getExtsValue(it.exts, "c8")
                if (list.isEmpty()) {
                    showToast(R.string.desc_toast_no_data_tyre)
                    return@setOnClickListener
                }
                val type = object : TypeToken<List<List<String>>>() {}
                val data: List<List<String>> = GsonUtil.gson.fromJson(list, type.type)
                DataUtil.psiTyres = data
                startActivityTo<TyreInfoActivity>(this) {
                    putExtra(Keys.INTENT_TITLE, if (mViewModel.isPlate) it.carPlate else it.carName)
                }
            }
        }
    }

    private val operInfoAdapter by lazy { OperInfoAdapter(FunType.POPUP) }

    private fun handleOper() {
        mInfoVB.rvType.isVisible = UserConstant.loginType == Keys.LOGIN_TYPE_USER
        mInfoVB.rvType.layoutManager = GridLayoutManager(this, 6)
        mInfoVB.rvType.adapter = operInfoAdapter
        operInfoAdapter.setList(InfoSetModel.getChooseList(FunType.POPUP))
        operInfoAdapter.isCanTalk = false
        operInfoAdapter.setOnItemClickListener { adapter, view, position ->
            val info = operInfoAdapter.data[position]
            if (!info.isCheckable) {
                R.string.toast_check_other_menu.toast(this)
                return@setOnItemClickListener
            }
            when (info.key) {

                MenuKey.MENU_916 -> {
                    startActivityTo<CarInfoActivity>(this) {
                        putExtra(Keys.INTENT_CAR_ID, mViewModel.carId)
                    }
                }

                FunKey.FUN_NAVI -> {
                    //退出导航组件
                    AmapNaviPage.getInstance().exitRouteActivity();

                    mViewModel.gpsDetail?.run {
                        startActivityTo<NaviActivity>(this@PopupActivity) {
                            putExtra(Keys.INTENT_PLATE, carPlate)
                            putExtra("eLat", glat)
                            putExtra("eLng", glng)
                            putExtra("bLat", blat)
                            putExtra("bLng", blng)
                        }
                    }
                }

                FunKey.FUN_CALL -> {
                    if (mViewModel.driverInfo.isNotEmpty()) {
                        if (mViewModel.driverInfo.size == 1) {
                            ToolsUtil.talkPhone(
                                this,
                                mViewModel.driverInfo[0].driverPhone
                            )
                        } else {
                            mDriversPopup.show(
                                this.window.decorView,
                                mViewModel.driverInfo
                            )
                        }
                    } else {
                        R.string.desc_no_phone.toast(this)
                    }
                }

                else -> {
                    InfoSetModel.startFunActivity(
                        this,
                        ActivityUtil.getActivityByKey(info.key),
                        mViewModel.gpsDetail
                    )
                }
            }
        }
    }

    private val runSpeed by lazy { getString(R.string.desc_run_speed) }
    private val dayMile by lazy { getString(R.string.desc_day_mile) }

    @SuppressLint("SetTextI18n")
    fun initInfo() {
        mViewModel.gpsDetail?.run {
            mInfoVB.tvCarRunSpeed.text = "$speed ${Units.speed}\n$runSpeed"
            mInfoVB.tvCarRunStop.text = runStopTime
            mInfoVB.tvCarDayMile.text = "$preMile ${Units.km}\n$dayMile"
            mInfoVB.tvCarTotalMile.text = "$mile ${Units.km}"
            mInfoVB.tvCarTime.text = "${getString(R.string.desc_location_time)}：$time"
            mInfoVB.tvSatl.text = "${getString(R.string.desc_marker_loaction)}${satl.split("-")[0]}"
            mInfoVB.tvSgn.text = "${getString(R.string.desc_marker_sgn)}${sgn.split("-")[0]}"
            ColorUtil.lineState(mInfoVB.tvOnLine, state)
            val title = if (mViewModel.isPlate) carPlate else carName
            ColorUtil.setPlateColor(
                mInfoVB.tvPlateArea,
                mInfoVB.tvPlateNum,
                plateColor,
                plateColorCode,
                title
            )
        }

        if (isShowRecycler) {
            showInfoRecycler()
        }

    }


    private val mAdapter by lazy { AlarmAdapter() }

    private val alarmsEntity = arrayListOf<VideoAlarm>()
    private fun initAlarms() {
        alarmsEntity.clear()
        alarmsEntity.add(VideoAlarm(R.mipmap.video_alarm_1, R.string.desc_video_alarm_1))
        alarmsEntity.add(VideoAlarm(R.mipmap.video_alarm_2, R.string.desc_video_alarm_2))
        alarmsEntity.add(VideoAlarm(R.mipmap.video_alarm_3, R.string.desc_video_alarm_3))
        alarmsEntity.add(VideoAlarm(R.mipmap.video_alarm_4, R.string.desc_video_alarm_4))
        alarmsEntity.add(VideoAlarm(R.mipmap.video_alarm_5, R.string.desc_video_alarm_5))
    }

    override fun onResume() {
        super.onResume()
        mViewModel.isHidden = false

        mViewModel.carId?.let {
            mViewModel.startTime(it)
            ToolsUtil.startAmin(binding.ivRefresh)
            binding.rlRefresh.isVisible = true
        }
        operInfoAdapter.setList(InfoSetModel.getChooseList(FunType.POPUP))
    }

    override fun onPause() {
        super.onPause()
        mViewModel.stopTime()
        ToolsUtil.stopAmin(binding.ivRefresh)
        binding.rlRefresh.isVisible = false
        mViewModel.isHidden = true
    }

    override fun onDestroy() {
        super.onDestroy()
        ToolsUtil.stopAmin(binding.ivRefresh)
        BitmapUtil.clearLruCache()
    }


    inner class AlarmAdapter :
        BaseQuickAdapter<VideoAlarm, BaseViewHolder>(R.layout.item_video_alarm) {
        private val normal_: String = getString(R.string.desc_video_alarm_normal_)
        private val normal: String = getString(R.string.desc_video_alarm_normal)

        override fun convert(holder: BaseViewHolder, item: VideoAlarm) {
            holder.setText(R.id.tvAlarmName, item.alarmTitleId)
            holder.setImageResource(R.id.ivAlarmPic, item.alarmImgId)
            if (item.isNormal) {
                holder.setBackgroundResource(R.id.tvAlarmType, R.drawable.bg_alarm_normal_)
                holder.setText(R.id.tvAlarmType, normal_)
            } else {
                holder.setBackgroundResource(R.id.tvAlarmType, R.drawable.bg_alarm_normal)
                holder.setText(R.id.tvAlarmType, normal)
            }
        }
    }
}